
import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('测试界面'),
      ),
      body: TestWidget(),
    ),
  ));
}

class TestWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return TestState();
  }
}

class TestState extends State<TestWidget> {
  //获取插件与原生Native的交互通道
  static const platForm = const MethodChannel('com.willian.flutterapp/jump_plugin');

  //具体要做的功能
  Future<Null> _goToNativeActivity() async {
    String result = await platForm.invokeMethod('GoToOneAct');
    print(result);
  }

  // 具体要做的功能
  Future<Null> _sendDataToNative() async {
    Map<String, String> map = {"flutter": "我是flutter 传递过来的"};
    String result = await platForm.invokeMethod('mapData', map);
    print(result);
  }

  String nativeBackString = 'Not return';

  Future<void> _invokeNativeGetResult() async {
    String backString;
    try {
      // 调用原生方法并传参，以及等待原生返回结果数据
      var result = await platForm.invokeMethod('getNativeResult', {'key1':'value1','key2':'value2'});
      backString = 'Native return $result';
    } on PlatformException catch (e) {
      backString = "Failed to get native return: '${e.message}'.";
    }

    setState(() {
      nativeBackString = backString;
    });
  }

  String mediaCall(BuildContext context){
    var media = MediaQuery.of(context);
    print(media.toString());
    print("设备像素密度:" + media.devicePixelRatio.toString());
    print(media.orientation);
    print("屏幕：" + media.size.toString());
    print('状态栏高度：' + media.padding.top.toString());
    return media.padding.toString();
  }

  Future<dynamic> _handel(MethodCall methodCall){
    String backNative = "failure";
    if(methodCall.method == 'flutterMedia'){
      print("flutter 参数：" + methodCall.arguments.toString());
      backNative = mediaCall(this.context);
    }
    return Future.value(backNative);
  }

  //接收来自native的消息
  static const receiveFromNative = const EventChannel('com.willian.flutterapp/native_send_plugin');
  StreamSubscription _streamSubscription;
  var _currentCount;

  @override
  void initState() {
    super.initState();

    //开启监听
    if (_streamSubscription == null) {
      _streamSubscription = receiveFromNative.receiveBroadcastStream().listen((Object event) {
        setState(() {
          _currentCount = event;
          print("flutter: ChannelPage: $event");
        });
      }, onError: (Object error) {
        setState(() {
          _currentCount = "计时器异常";
          print(error);
        });
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
    //取消监听
    if (_streamSubscription != null) {
      _streamSubscription.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {

    // flutter 注册原生监听方法
    platForm.setMethodCallHandler(_handel);

    return Container(
        child: Column(
      children: <Widget>[
        RaisedButton(
          child: Text('跳转到原生activity'),
          onPressed: () {
            _goToNativeActivity();
          },
        ),
        RaisedButton(
          child: Text('让原生接收到数据'),
          onPressed: () {
            _sendDataToNative();
          },
        ),
        RaisedButton(
          child: Text('原生传递过来的值 $nativeBackString'),
          onPressed: () {
            _invokeNativeGetResult();
          },
        )
      ],
    ));
  }
}
